package ru.spb.osll.myfit.client.view;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import ru.spb.osll.myfit.client.dialog.ErrorDialog;
import ru.spb.osll.myfit.client.manager.PageExecutingManager;
import ru.spb.osll.myfit.client.service.PageExecutingService;
import ru.spb.osll.myfit.client.service.PageExecutingServiceAsync;
import ru.spb.osll.myfit.client.widget.PageExecutingListener;
import ru.spb.osll.myfit.common.PageExecutingResult;

import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class TestResultsViewController implements IViewController {

  private ErrorDialog m_errorDialog = new ErrorDialog();
  /**
   * Create a remote service proxy to talk to the server-side Fit service.
   */
  private final PageExecutingServiceAsync m_pageExecutingService =
                                  GWT.create(PageExecutingService.class);

  @Override
  public IView getView(String address) {
    final TestResultsView view = new TestResultsView();
    PageExecutingManager manager = new PageExecutingManager();
    PageExecutingListener listener = new PageExecutingListener() {
        @Override
        public void processPageExecutingResult(PageExecutingResult result) {
            view.updateResult(result);
        }

        @Override
        public void finish() {
        }
    };
    addResults(view, manager, listener);
    return view;
  }

  private void addResults(final TestResultsView view, final PageExecutingManager manager, final PageExecutingListener listener) {
    m_pageExecutingService.getTestResults(new AsyncCallback<Set<PageExecutingResult>>() {
      public void onFailure(Throwable caught) {
        m_errorDialog.center();
      }

      public void onSuccess(Set<PageExecutingResult> list) {
        List<PageExecutingResult> results = new LinkedList<PageExecutingResult>(list);
        view.addResultToWidget(results);
        for(PageExecutingResult r : list){
            manager.addResultToListen(r);
            manager.addListener(r.getID(), listener);
        }
      }
    });
  }

}
